<template>
  <div v-loading="loading.all" class="phaseBefore">
    <span class="isExpand" @click="isExpand = !isExpand">
      <i :class="isExpand ? 'el-icon-arrow-right' : 'el-icon-arrow-left'" />
    </span>
    <el-row :gutter="15">
      <el-col :span="isExpand ? 18 : 24">
        <div v-loading="loading.node" class="" :current="current">
          <div class="list-table">
            <div class="tit-steps">
              <div class="lt">
                <i class="phase" />
                {{ $t('业务阶段') }}
              </div>
              <div class="rt">
                <el-select v-if="roundList && roundList.length > 1" v-model="roundId" class="roundList" style="width: 150px;margin-right: 10px;" size="mini" filterable @change="roundChange">
                  <el-option
                    v-for="item in roundList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
                <el-button
                  v-if="addInvest === 'Y' "
                  size="mini"
                  class="primary-light-2"
                  @click="addInvestHandle"
                >
                  {{ $t('新增投资') }}
                </el-button>
                <el-button
                  v-if="busType === 'deal' && canTermination && !lastNode"
                  size="mini"
                  class="danger-light-1"
                  @click="dealTermination"
                >
                  {{ $t('终止项目') }}
                </el-button>
                <el-button
                  v-if=" !lastNode && (isSubmitStage || isSubmitStage === undefined)"
                  size="mini"
                  type="primary"
                  class="primary-light-3"
                  :disabled="!checkNextNode"
                  @click="checkCommitNextNode"
                >
                  {{ $t('提交下一阶段') }}
                </el-button>
              </div>
            </div>
            <!--流程一级节点-->
            <div id="searchBar" class="searchBar wizard">
              <ul>
                <li
                  v-for="(node) in parentNodeList"
                  :key="node.id"
                  :class="node.class !== undefined ?node.class:''"
                  @click="getChildrenNode(node.nodeId)"
                >
                  <div class="phaseStyle">
                    <span :class="{bold:currentNodeId === node.nodeId}"> {{ $t(node.wfConfigNode.nodeName) }}</span>
                  </div>
                </li>
              </ul>
            </div>
          </div>
          <div class="list-table noPad mt15">
            <!--流程二级节点-->
            <div class="steps-content" :class="{'stretch-step' : childrenNodeList.length > 8 }">
              <el-tabs v-model="currentChildIndex" :stretch="childrenNodeList.length > 8" @tab-click="confirmHandle(null)">
                <el-tab-pane v-for="childrenNode in childrenNodeList" :key="childrenNode.id" :name="childrenNode.id" :label="$t(childrenNode.wfConfigNode.nodeName)" />
              </el-tabs>
            </div>
            <div v-show="currentChildNode.viewNode" class="state">
              <div v-if="currentChildNode.operation !== 'N'" class="startKnob">
                <div v-show="currentChildNode.processKey" class="lt defaltBtn" style="line-height: 28px;display: flex">
                  <ProcessStatus :status="currentChildNode.actStatus" :show-record="false" />
                </div>
                <div class="rt">
                  <ul class="state-btn">
                    <li v-show="historyApproval.length > 1" style="margin-right: 10px;">
                      {{ $t('历史申请记录') }}:
                      <el-select v-model="currentChildId" size="mini" :placeholder="$t('请选择')" @change="historyChange(currentChildId)">
                        <el-option
                          v-for="his in historyApproval"
                          :key="his.id"
                          :label="$t('第{num}次启动',{'num':his.restartNum})"
                          :value="his.id"
                        >
                          <span style="float: left"> {{ $t('第{num}次启动',{'num':his.restartNum}) }}</span>
                          <span style="float: right; color: #8492a6; font-size: 13px"><ProcessStatus :status="his.actStatus" :show-record="false" /></span>
                        </el-option>
                      </el-select>
                    </li>
                    <li v-if="(currentChildNode.actStatus === 'N' || currentChildNode.actStatus === 'Z' || !currentChildNode.actStatus) && currentChildNode.viewNode && currentChildNode.editNode" class="mr10">
                      <el-button size="mini" class="primary-light-2" @click="submitForm('save')">{{ $t('保存表单') }}</el-button>
                    </li>
                    <li v-if="(currentChildNode.actStatus === 'N' || currentChildNode.actStatus === 'Z' || !currentChildNode.actStatus) && currentChildNode.processKey && currentChildNode.startProcess && currentChildNode.editNode" class="mr10">
                      <el-button type="primary" size="mini" class="primary-light-3" @click="submitForm('process')">{{ $t("保存并启动流程") }}</el-button>
                    </li>
                    <li v-if="currentChildNode.restart && currentChildNode.editNode" class="mr10">
                      <el-button size="mini" class="primary-light-2" @click="restart()">{{ $t("再次发起") }}</el-button>
                    </li>
                    <li v-if="(currentChildNode.actStatus === 'N' || currentChildNode.actStatus === 'Z' || !currentChildNode.actStatus) && (currentChildNode.immunity)" class="mr10">
                      <el-button type="primary" size="mini" class="warn-light-1" @click="immunityProcess('process')">{{ $t("豁免") }}</el-button>
                    </li>
                    <li v-if="currentChildNode.actStatus === 'D' && currentChildNode.editNode" class="mr10">
                      <el-button size="mini" class="danger-light-1" @click="stopProcess(currentChildNode)">{{ $t("终止流程") }}</el-button>
                    </li>
                    <li v-if="currentChildNode.processKey" class="mr10">
                      <act-view-flow-chart :process-key="currentChildNode.processKey" />
                    </li>
                    <li v-if="currentChildNode.actStatus === 'W' || currentChildNode.actStatus === 'H'" class="">
                      <el-button size="mini" class="primary-light-2" @click="doPrint">{{ $t('打印') }}</el-button>
                    </li>
                  </ul>
                </div>
              </div>
              <!-- 流程表单 -->
              <div v-loading="loading.form" class="procesInfo">
                <div v-show="currentChildNode.viewNode">
                  <!--            <div class="area-header"><span class="area-header-title">{{ $t('基本信息') }}</span></div>-->
                  <component :is="dynaPath" ref="actFormPath" />
                </div>
                <div v-show="currentChildNode.viewNode !== undefined && currentChildNode.viewNode !== null && !currentChildNode.viewNode">
                  <el-row style="height: 500px" align="middle" justify="center">
                    <el-col :span="24">
                      <div style="height: 500px;width: 100%;text-align:center;margin:200px auto;font-size:30px">
                        {{ $t('您无权查看该节点') }}
                      </div>
                    </el-col>
                  </el-row>
                </div>
                <!--流转记录-->
                <div v-show="currentChildNode.viewNode" v-if="currentChildNode.actId !== '' && currentChildNode.actId !== null && approvalRecordShow" class="list-table" style="margin-top: 17px">
                  <approval-record ref="record" :act-id="currentChildNode.actId" />

                  <!--流程图-->
                  <act-flow-chart ref="flowChat" :act-id="currentChildNode.actId" />
                </div>

              </div>
              <!-- 打印流程表单 -->
              <div id="print" ref="print" v-loading="loading.form" class="procesInfo" style="display:none;">
                <div v-show="currentChildNode.viewNode" class="">
                  <!--            <div class="area-header"><span class="area-header-title">{{ $t('基本信息') }}</span></div>-->
                  <component :is="dynaPath" ref="viewFormPath" />
                </div>
                <div v-show="currentChildNode.viewNode !== undefined && currentChildNode.viewNode !== null && !currentChildNode.viewNode">
                  <el-row style="height: 500px" align="middle" justify="center">
                    <el-col :span="24">
                      <div style="height: 500px;width: 100%;text-align:center;margin:200px auto;font-size:30px">
                        {{ $t('您无权查看该节点') }}
                      </div>
                    </el-col>
                  </el-row>
                </div>
                <!--流转记录-->
                <div v-show="currentChildNode.viewNode" v-if="currentChildNode.actId !== '' && currentChildNode.actId !== null && approvalRecordShow" class="list-table" style="margin-top: 17px">
                  <approval-record :act-id="currentChildNode.actId" />

                  <!--流程图-->
                  <act-flow-chart :act-id="currentChildNode.actId" />
                </div>

              </div>

            </div>
          </div>
        </div>
      </el-col>
      <el-col v-if="isExpand" :span="6">
        <miniProcess ref="miniProcess" :children-node-list="childrenNodeList" :current-node-id="currentNodeId" :current-child-index="currentChildIndex" :display-card="displayCard" />
      </el-col>
    </el-row>

    <el-dialog :title="$t('终止/暂缓项目')" :visible.sync="dealTerminationOpen" width="500px" height="200px" :close-on-click-modal="false" :lock-scroll="false">
      <el-form ref="form" v-loading="terminationLoading" class="dataForm" :model="dealTerminationForm" :rules="dealTerminationRules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <!-- 单选 终止/暂缓 -->
            <el-form-item :label="$t('项目状态')" prop="terminationType">
              <el-radio-group v-model="dealTerminationForm.terminationType">
                <el-radio label="ZH">{{ $t('暂缓') }}</el-radio>
                <el-radio label="ZZ">{{ $t('终止') }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('原因')" prop="terminationReason">
              <el-input v-model="dealTerminationForm.terminationReason" type="textarea" :placeholder="$t('原因')" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 提醒设置 -->
      <el-dialog v-if="remindOpen" :title="$t('项目提醒')" :visible.sync="remindOpen" style="width: 66%;height: 78%;top: 10%;left: 14%;z-index: 2005;" :destroy-on-close="true" :lock-scroll="false" custom-class="dialogForm" append-to-body>
        <remindEvent ref="remindEvent" :waite-save="true" :has-permi="'deal:dealbase'" :is-show-deal-team="true" :is-show-role="true" :is-show-user="true" reminder-type="deal_base" @saveRemindEvent="saveRemindEvent" />
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDealTermination">{{ $t("取消") }}</el-button>
        <el-button @click="openRemind">{{ $t('提醒') }}</el-button>
        <el-button type="primary" @click="submitDealTermination">{{ $t("确定") }}</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改事项申请对话框 -->
    <el-dialog :title="$t('查看流程图')" :visible.sync="showFlowChartOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogFormPcwMedical" append-to-body>
      <show-flow-chart :process-definition-key="currentChildNode.processKey" />
    </el-dialog>

    <!-- 添加投资对话框 -->
    <el-dialog :title="$t('新增投资')" :visible.sync="addInvestOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm dialog-height" width="30%" append-to-body>
      <add-invest-form ref="addInvestForm" />
    </el-dialog>
    <div v-show="false" id="hideContainer" />
  </div>
</template>

<script>
import {
  getParentNode,
  getChildrenNode,
  getNodeFormUrl,
  bindingDataId,
  restart,
  getHistoryApproval,
  getWfBusNode,
  checkCommitNextNode,
  commitNextNode,
  immunityProcess
} from '@/api/act/busFlow/wfBusNode'
import { getAsyncComponent } from '@/utils'
import { startProcessByNode, stop } from '@/api/act/process/actProcess'
import approvalRecord from '@/components/Act/ApprovalRecord'
import miniProcess from './miniProcess'
// 项目提醒设置
import remindEvent from '@/components/remind/sysRemindEvent.vue'
import { config } from '@/utils'
import { dealTermination, getDealStatus } from '@/api/base/deal/dealBase'
import ActFlowChart from '@/views/act/process/actFlowChart'
import ShowFlowChart from '@/views/act/process/showFlowChart'
import ActViewFlowChart from '@/views/act/task/actViewFlowChart'
import AddInvestForm from './form/addInvestForm'
import { importComponent } from '@/qiankun/index'
import { appsVariable } from '@/qiankun/registerApp'
import { saveDataSysRemindEvent } from '@/api/system/sysremindevent/sysRemindEvent'
const { dealBasepath } = config

export default {
  name: 'ProcessPhase',
  components: {
    remindEvent,
    ActViewFlowChart,
    ShowFlowChart,
    ActFlowChart,
    approvalRecord,
    AddInvestForm,
    miniProcess
  },
  props: {
    busId: {
      type: String,
      default: () => ''
    },
    busType: {
      type: String,
      default: () => ''
    },
    busName: {
      type: String,
      default: () => ''
    },
    displayCard: {
      type: String,
      default: () => 'ask,confirm,approve,file,plan,tag,invest',
      description: '显示的Card字符串，以,分隔(ask:当前阶段要求，confirm：当前阶段确认事项，approve：提交前需完成审批，file：当前阶段需上传文件，plan：项目计划，tag：标签)'
    }
  },
  data() {
    return {
      formDisabled: false,
      businessName: undefined,
      dynaPath: '',
      activeClass: 0,
      current: 0,
      phase: 3,
      isCollapse: false,
      dialogVisible: false,
      dialogVisible1: false,
      tableData: [],
      activeName: '0',
      activeName1: 'first',
      formLabelWidth: '120px',
      searchBarFixed: false,
      // 是否展示新增投资
      addInvest: undefined,
      // 当前所有轮次集合
      roundList: [],
      // 当前选中的轮次
      roundId: undefined,
      // 查看流程图的遮罩层是否展示
      showFlowChartOpen: false,
      // 新增投资表单是否展示
      addInvestOpen: false,
      // 等待框
      loading: {
        // 节点区域等待框
        node: true,
        // 表单区域等待框
        form: true,
        // 整体区域等待框
        all: false
      },
      // 是否可以提交下一阶段
      checkNextNode: false,
      // 当前是否处在流程的最后一个阶段
      lastNode: false,
      // 是否展示审批记录
      approvalRecordShow: true,
      // 一级节点集合
      parentNodeList: [],
      // 二级节点集合
      childrenNodeList: [],
      // 当前一级阶段
      currentNode: {},
      // 当前一级阶段的nodeId
      currentNodeId: '',
      // 当前二级节点
      currentChildNode: {
        viewNode: true
      },
      // 当前选中的二级节点的序号
      currentChildIndex: 0,
      // 当前二级节点的ID
      currentChildId: undefined,
      // 当前节点历史审批记录
      historyApproval: [],
      // 当前查看的历史节点的ID
      historyApprovalId: undefined,
      // 是否显示项目终止
      canTermination: true,
      // 终止项目表单信息
      dealTerminationForm: {},
      // 终止项目页面是否打开
      dealTerminationOpen: false,
      // 子表单的校验项
      formRulesTemp: {},
      dealTerminationRules: {
        terminationReason: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        terminationType: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ]
      },
      isSubmitStage: false,
      remindOpen: false,
      dealRemindEventData: undefined,
      terminationLoading: false,
      isExpand: false
    }
  },

  // 页面加载后执行
  mounted() {
    // 查询一级节点
    this.getParentNode(this.busType, this.busId)

    // 获取是否能够终止项目
    this.getCanTermination()

    // 获取是否能够提交下一阶段
    this.getIsSubmitStage()

    this.$nextTick(() => {
      if (dealBasepath?.component !== undefined) {
        this.dynaPath = dealBasepath.component
      }
    })
  },

  methods: {
    doPrint() {
      this.$print(this.$refs.print)
    },
    hideProcess(flag = true) {
      this.approvalRecordShow = flag
    },
    // 查询一级节点
    getParentNode(busType, busId, roundId) {
      if (!busType) {
        busType = this.busType
      }
      getParentNode(busType, busId, roundId).then(response => {
        console.log('查询的一级节点的数据', response)
        if (response.data === 0) {
          this.$message.error('未配置流程阶段')
          this.loading.node = false
          this.loading.form = false
          return
        }

        // 轮次数据
        this.roundList = response.datas.roundList
        // 当前轮次ID
        this.roundId = response.datas.roundId
        // 一级节点集合
        this.parentNodeList = response.data
        // 是否展示提交下一阶段按钮
        this.isSubmitStage = response.datas.isSubmitStage
        // 当前选中的一级节点
        this.currentNode = response.datas.currentNode
        // 是否配置了新增投资流程
        this.addInvest = response.datas.addInvest
        // 查询是否可以提交至下一节点
        this.getCheckNextNode()
        // 默认点击当前节点（查询对应的二级节点）
        this.getChildrenNode(this.currentNode.nodeId)
        // 设置节点颜色(当前节点及以前是蓝色，其他是灰色)
        for (var i = 0; i < this.parentNodeList.length; i++) {
          this.parentNodeList[i].class = 'active'
          if (this.parentNodeList[i].nodeId === this.currentNode.nodeId) {
            if (i === this.parentNodeList.length - 1) {
              this.lastNode = true
            }
            return
          }
        }
      })
    },
    // 一级点击点击事件 - 查询二级节点
    getChildrenNode(parentNodeId) {
      this.currentNodeId = parentNodeId
      getChildrenNode(parentNodeId, this.busId, this.roundId).then(response => {
        this.childrenNodeList = response.data
        this.loading.node = false
        // 点击默认的二级节点
        // 默认点击第一个节点
        this.currentChildIndex = response.datas.currentChildIndex
        this.confirmHandle(response.datas.currentChildIndex)
      })
    },
    confirmHandle(id) {
      // if (this.currentChildNode.actFormPath) {
      //   var _form = this.$refs.actFormPath.form
      //   if (JSON.stringify(_form) === sessionStorage.getItem('cacheForm')) {
      //     console.log('表单没变化')
      //     this.childrenNodeClick(id)
      //   } else {
      //     if (this.currentChildNode.actStatus !== 'N') {
      //       this.childrenNodeClick(id)
      //     } else {
      //       console.log('表单变化')
      //       this.$confirm('表单内容已改变, 是否保存?', '提示', {
      //         confirmButtonText: '确定',
      //         cancelButtonText: '取消',
      //         type: 'warning',
      //         closeOnClickModal: false,
      //         closeOnPressEscape: false
      //       }).then(() => {
      //         console.log('保存')
      //         this.submitForm('save')
      //         this.childrenNodeClick(id)
      //       }).catch(() => {
      //         console.log('取消')
      //         this.childrenNodeClick(id)
      //       })
      //     }
      //   }
      // } else {
      this.childrenNodeClick(id)
      // }
    },
    // 二级节点点击事件
    childrenNodeClick(id) {
      this.loading.form = true
      id = (id !== null && id !== undefined) ? id : this.currentChildIndex
      // 如果ID为空则是没有配置流程二级节点
      if (id !== null && id !== undefined && id !== '') {
        // 根据ID查询wfBusNode表记录
        getWfBusNode(id).then(response => {
          this.currentChildNode = response.data
          // 打印增加标题
          var nodeName = response.data.wfConfigNode.nodeName
          document.title = this.busName + '-' + nodeName

          // 查询该节点是否有历史的审批记录
          this.getHistoryApproval(this.currentChildNode.id)
          getNodeFormUrl(this.currentChildNode).then(response => {
            // 当前节点的表单地址
            this.currentChildNode.actFormPath = response.data
            this.importFormPath(response.data)
            // 刷新流转记录
            this.refreshRecord()
            if (this.$refs.miniProcess?.getParentNodeRightData !== undefined) {
              this.$refs.miniProcess.getParentNodeRightData()
            }
          })
        })
      } else {
        this.loading.form = false
        this.$message.error('流程配置错误,请配置流程二级节点')
      }
    },
    // 引入表单组件
    async importFormPath(menuPath) {
      console.log('menuPath', menuPath)
      // 循环所有子应用，如果是子应用的菜单，则引用他们的组件
      const apps = appsVariable()
      const newPath = menuPath.lastIndexOf('\/')
      var strPath = ''
      var subAppName
      var isSubAppMenuPath = false
      var subApp
      if (apps) {
        apps.forEach(element => {
          if (menuPath && menuPath.includes(element.name)) {
            isSubAppMenuPath = true
            subAppName = element.name
            subApp = element
            return
          }
        })
      }
      if (isSubAppMenuPath) {
        strPath = menuPath.substring(newPath + 1, menuPath.length)
        const componentName = strPath + '_' + subAppName
        // 导入子应用的组件
        await importComponent(subApp, componentName)
        this.actFormPath = componentName
        this.dynaPath = componentName
        console.log(this.menuPath)
      } else {
        this.dynaPath = getAsyncComponent(menuPath)
      }
      this.$bus.$once('async_done', () => {
        this.$nextTick(async function() {
          const data = {}
          data.id = this.currentChildNode.dataId
          data.formId = this.currentChildNode.formId
          // 如果id没有值就统一设置为undefined,方便子页面判断
          if (data.id === null || data.id === '') {
            data.id = undefined
          }
          // 默认流程标题
          var actTitle = this.busName + '-' + this.$t(this.currentChildNode.wfConfigNode.nodeName)

          // file对象中增加业务ID
          if (!this.currentChildNode.actStatus || this.currentChildNode.actStatus === 'N' || this.currentChildNode.actStatus === 'Z') {
            data.fileList = this.currentChildNode.fileList
          }

          // if (data.fileList) {
            // data.fileList.forEach(item => {
            //   item.businessId = this.currentChildNode.busId
            // })
          // }
          data.wfNodeId = this.currentChildNode.id
          data.actTitle = actTitle
          data.processKey = this.currentChildNode.processKey
          data.roundId = this.roundId
          data.nodeName = this.currentChildNode.wfConfigNode.nodeName
          data.meeting = this.currentChildNode.meeting
          data.meetingType = this.currentChildNode.meetingType

          this.$refs.actFormPath && await this.$refs.actFormPath.init(data)
          // var _this = this
          // this.$nextTick(() => {
          //   var timer = null // 声明定时器
          //   function check() { // 检查是否执行完成
          //     if (_this.$refs.actFormPath.loading === false) {
          //         // console.log('_this.$refs.actFormPath', _this.$refs.actFormPath)
          //         var cacheForm = _this.$refs.actFormPath.form
          //         sessionStorage.setItem('cacheForm', JSON.stringify(cacheForm))
          //         if (!timer) clearTimeout(timer) //  清除定时器
          //     } else timer = setTimeout(check, 0) //  自我调用
          //   }
          //   check()
          // })
          this.$refs.viewFormPath && await this.$refs.viewFormPath.init(data)
          if (this.$refs.actFormPath._data.form.actTitle === undefined) {
            this.$nextTick(() => {
              this.$refs.actFormPath._data.form.actTitle = actTitle
              this.$refs.viewFormPath._data.form.actTitle = actTitle
            })
          }
          // 控制保存按钮等按钮是否隐藏
          console.log(this.$refs)
          this.$refs.actFormPath._data.btnHide = true
          console.log(this.$refs)
          this.$refs.viewFormPath._data.btnHide = true
          // 控制其他按钮是否隐藏
          this.formDisabled = false
          if (this.currentChildNode.actId !== null && this.currentChildNode.actId !== '' && this.currentChildNode.actStatus !== 'Z') {
            this.$refs.actFormPath._data.otherBtnHide = true
            this.$refs.viewFormPath._data.otherBtnHide = true
            this.formDisabled = true
          }
        })
      })
      this.loading.form = false
    },
    // 保存表单时清楚校验
    clearCheck(type) {
      console.log(type, '流程类型')
      if (type === 'save') {
        if (this.$refs.actFormPath.rules) {
          window.localStorage.setItem('fileConfigRequired', false)
          var keys = Object.keys(this.$refs.actFormPath.rules)
          // 普通表单处理
          if (this.$refs.actFormPath.$refs.form?.clearValidate) {
            this.$refs.actFormPath.$refs.form.clearValidate()
          }
          // 多sheet页表单处理
          if (this.$refs.actFormPath?.clearValidate) {
            this.$refs.actFormPath.clearValidate()
          }

          if (keys.length > 0) {
            this.formRulesTemp = {}
            for (let i = 0; i < keys.length; i++) {
              this.formRulesTemp[keys[i]] = this.$refs.actFormPath.rules[keys[i]]
              this.$refs.actFormPath.rules[keys[i]] = []
            }
          }
        }
      }
    },
    // 提交流程时校验
    addCheck(type) {
      if (type === 'save') {
        window.localStorage.setItem('fileConfigRequired', true)
        var keys = Object.keys(this.formRulesTemp)
        if (keys.length > 0) {
          for (let i = 0; i < keys.length; i++) {
            this.$refs.actFormPath.rules[keys[i]] = this.formRulesTemp[keys[i]]
          }
        }
      }
    },
    /**
     * 保存表单和保存并启动流程
     * @param type  保存表单：save  保存并启动流程:process
     */
    submitForm(type) {
      console.log(type)
      // 保存表单时清除校验
      if (this.currentChildNode.processKey) {
        this.clearCheck(type)
      }

      // 设置必传附件校验
      this.checkFileRequired(type)

      // 掉用子组件保存数据
      this.$refs.actFormPath.submitForm('actSave').then((dataId) => {
        // 恢复校验
        if (this.currentChildNode.processKey) {
          this.addCheck(type)
        }
        console.log(this.currentChildNode.id, dataId)
        if (dataId === undefined) {
            dataId = this.currentChildNode.dataId
        }

        // 将dataId保存到wfBusNode表
        bindingDataId(this.currentChildNode.id, dataId).then((response) => {
          if (response.code === 200) {
            // 保存结束后, 重新加载该表单. 目的是为了让子表及附件获取已经录入的ID. 防止再次保存造成新增重复
            this.childrenNodeClick(this.currentChildNode.id)
            // 点击的按钮是保存并启动流程
            if (type === 'process') {
              if (this.currentChildNode.processKey !== '' && this.currentChildNode.processKey !== null) {
                // 启动流程
                this.startProcess(response.data)
              } else {
                this.$message.error(this.$t('流程启动失败,该节点未配置流程'))
              }
            }
          } else {
            this.msgError(response.msg)
          }
        })
      }).catch(e => {
        // 恢复校验
        this.addCheck(type)
        console.error('error', e)
        this.msgError(this.$t('保存失败,数据未绑定成功'))
      })
    },
    // 启动流程
    startProcess: function() {
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      if (this.$refs.actFormPath._data.form !== undefined && this.$refs.actFormPath._data.form.actTitle !== undefined) {
        processData.title = '「' + this.busName + '」' + this.currentChildNode.wfConfigNode.nodeName + ':' + this.$refs.actFormPath._data.form.actTitle
      } else {
        processData.title = '「' + this.busName + '」' + this.currentChildNode.wfConfigNode.nodeName
      }
      // 业务表名
      processData.dataTable = 'wf_bus_node'
      // 业务ID
      processData.dataId = this.currentChildNode.id
      // 业务表单地址
      processData.formPath = this.currentChildNode.actFormPath
      // 使用的流程表单ID
      processData.formId = this.currentChildNode.formId
      // 打印地址
      var actViewPath = processData.formPath.replace(/(.*)Form/, '$1View')
      processData.viewPath = actViewPath

      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.processKey = this.currentChildNode.processKey
      startProcessByNode(processData, () => {
        // 从新点击二级节点
        this.childrenNodeClick(this.currentChildNode.id)
      })
    },
    // 再次启动
    restart() {
      this.$confirm(this.$t('是否确认再次发起') + '?', this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      })
        .then(() => {
           restart(this.currentChildNode).then((response) => {
             this.childrenNodeClick(response.data.id)
           })
        })
        .catch(function() {})
    },
    /**
     * 终止流程
     * @param data 流程实例ID
     */
     stopProcess(data) {
      this.$prompt('', this.$t('终止原因'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        inputErrorMessage: this.$t('终止原因不能为空'),
        inputValidator: (reason) => {
          if (reason === null || reason === '' || reason.trim().length < 1) {
            return this.$t('终止原因不能为空')
          }
        }
      }).then(({ value }) => {
        this.loading.all = true
        stop(data.actId, value).then(response => {
          if (response.code === 200) {
            this.currentChildNode.actStatus = 'Z'
            this.msgSuccess(this.$t('终止成功'))
            this.loading.all = false
            // 刷新页面
            this.childrenNodeClick()
          }
        }).catch(() => {
          this.loading.all = false
          // 刷新页面
          this.childrenNodeClick()
        })
      }).catch(() => {
      })
    },
    // 刷新流转记录
    refreshRecord() {
      this.approvalRecordShow = false
      this.$nextTick(() => {
        this.approvalRecordShow = true
      })
    },
    // 查询该节点的历史审批记录
    getHistoryApproval(id) {
      getHistoryApproval(id).then((response) => {
        if (response.code === 200) {
          this.historyApproval = response.data
          // 当前二级节点的ID
          this.currentChildId = id
        } else {
          this.msgError(response.msg)
        }
      })
    },
    // 历史节点选中事件
    historyChange(id) {
      getWfBusNode(id).then((response) => {
        if (response.code === 200) {
          this.currentChildNode = response.data
          this.childrenNodeClick(this.currentChildNode.id)
        }
      })
    },
    // 提交下一节点
    checkCommitNextNode() {
      checkCommitNextNode(this.currentNode.id).then((response) => {
        if (response.code === 200) {
          // 依赖但没有完成的节点名称
          var realNodeName = response.data
          if (realNodeName.length > 0) {
            this.$message.error(this.$t('请先完成') + ':' + realNodeName)
          } else {
            // 切换节点
            this.commitNextNode(response.datas.nextNode)
          }
        }
      })
    },
    // 校验是否可以提交下一节点
    getCheckNextNode() {
      checkCommitNextNode(this.currentNode.id).then((response) => {
        if (response.code === 200) {
          // 依赖但没有完成的节点名称
          var realNodeName = response.data
          if (realNodeName.length > 0) {
            this.checkNextNode = false
          } else {
            this.checkNextNode = true
          }
        }
      })
    },
    // 提交下一节点
    commitNextNode(nextNode) {
      var tempName = nextNode.wfConfigNode.nodeName
      this.$confirm(this.$t('是否确认将项目提交至「{name}」节点', { name: this.$t(tempName) }), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      })
        .then(() => {
          return commitNextNode(this.currentNode.id)
        })
        .then(() => {
          this.getParentNode(this.busType, this.busId, this.roundId)
        })
        .catch(function() {})
    },
    // 终止项目
    dealTermination() {
      this.dealTerminationOpen = true
    },
    // 取消终止项目
    cancelDealTermination() {
      this.dealTerminationOpen = false
    },
    // 获取是否能够终止项目
    getCanTermination() {
       if (this.busType === 'deal') {
          getDealStatus(this.busId).then((response) => {
            if (response.data === 'ZZ') {
              this.canTermination = false
            }
          })
       }
    },
    // 获取是否可以提交下一阶段
    getIsSubmitStage() {
      this.isSubmitStage = false
    },
    // 确认终止项目
    submitDealTermination() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.terminationLoading = true
          dealTermination(this.busId, this.dealTerminationForm.terminationReason, this.dealTerminationForm.terminationType).then(() => {
            this.msgSuccess(this.$t('终止成功'))
            this.canTermination = false
            this.dealTerminationOpen = false
            // 保存项目提醒
            if (this.dealRemindEventData) {
              if (!this.dealRemindEventData.context.includes(window.location.href.toString())) {
                this.dealRemindEventData.context += '<br><p><a href="' + window.location.href.toString() + '" target="_blank" rel="noopener">' + this.$t('点击此处快速访问') + '</a></p>'
              }
              saveDataSysRemindEvent(this.dealRemindEventData)
            }
            this.terminationLoading = false
          }).catch(() => {
            this.terminationLoading = false
            this.canTermination = false
            this.dealTerminationOpen = false
          })
        }
      })
    },
    // 豁免流程
    immunityProcess() {
      this.$confirm(this.$t('是否确认豁免该节点'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      })
        .then(() => {
          return immunityProcess(this.currentChildNode.id)
        })
        .then(() => {
          this.getParentNode(this.busType, this.busId, this.roundId)
        })
        .catch(function() {})
    },
    // 查看当前节点的流程图
    // showNodeFlowChart(processDefinitionKey) {
    //   console.log(processDefinitionKey)
    //   this.showFlowChartOpen = true
    // }
    /**
     * 点击新增投资事件
     */
    addInvestHandle() {
       this.addInvestOpen = true
       this.$nextTick(() => {
         this.$refs.addInvestForm.init(this.busId, this.busType)
       })
    },
    /**
     * 轮次变更
     */
    roundChange(val) {
      this.getParentNode(this.busType, this.busId, val)
    },
    /**
     * 保存前必传附件校验设置
     * actFormPath表单init方法执行后会覆盖fileList, 目前拿不到接口返回的最新的
     * 数据, 所以放在提交前校验
     */
    checkFileRequired(type) {
      const wConfigNode = this.currentChildNode.wfConfigNode
      if (wConfigNode && wConfigNode.checkFile) {
        // this.$refs.actFormPath.pojo['filelist'] 拿到自定义表单的附件
        var fileList = (this.$refs.actFormPath.form && this.$refs.actFormPath.form.fileList) ? this.$refs.actFormPath.form.fileList
          : ((this.$refs.actFormPath.pojo && this.$refs.actFormPath.pojo['filelist']) ? this.$refs.actFormPath.pojo['filelist'] : [])
        if (wConfigNode.checkFile.length === 0) {
          // 配置中, 必填附件为空, 表单里的附件理论上都应该为非必填
          fileList.forEach(item => {
            item.checkRequired = 'false'
          })
        } else {
          // 配置中, 必填附件不为空, 看一下那个目录需要必填设置上必填标识
          var isProcessBtn = (this.currentChildNode.actStatus === 'N' || this.currentChildNode.actStatus === 'Z' || !this.currentChildNode.actStatus) && this.currentChildNode.processKey && this.currentChildNode.startProcess && this.currentChildNode.editNode
          fileList.forEach(item => {
            // true表示需要必填, 但是只有在启动流程时才生效, 保存时不需要必填
            if (type === 'save') {
              // 保存按钮不校验附件必填
              item.checkRequired = 'false'
            } else if (wConfigNode.checkFile.includes(item.directoryId) && type === 'process') {
              item.checkRequired = 'true'
            } else if (wConfigNode.checkFile.includes(item.directoryId) && !isProcessBtn) {
              // 如果页面上没有流程按钮, 也需要校验附件必填情况
              item.checkRequired = 'true'
            } else {
              item.checkRequired = 'false'
            }
          })
        }
      } else {
        var fileLists = (this.$refs.actFormPath.form && this.$refs.actFormPath.form.fileList) ? this.$refs.actFormPath.form.fileList
        : ((this.$refs.actFormPath.pojo && this.$refs.actFormPath.pojo['filelist']) ? this.$refs.actFormPath.pojo['filelist'] : [])
        if (type === 'save' && !this.isEmpty(fileLists)) {
          fileLists.forEach(item => {
            item.checkRequired = 'false'
          })
        }
      }
    },
    // 提醒设置
    openRemind() {
      this.remindOpen = true
      this.$nextTick(() => {
        if (this.dealRemindEventData) {
          this.$refs.remindEvent.initData(this.dealRemindEventData)
        } else {
          this.$refs.remindEvent.init(this.$route.query.id)
        }
      })
    },
    saveRemindEvent(data) {
      console.log(data, '要保存的提醒时间')
      this.dealRemindEventData = JSON.parse(data)
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .el-dialog.dialog-height{
  height: 45%;
}
/deep/ .el-dialog.dialog-min{
  height: 32%;
}
/deep/.roundList{
  input{
    height: 26px;
  }
}
.icon-button{
  padding: 6px 8px!important;
  font-size: 18px!important;
  font-weight: bold!important;
}
.icon--more{
  border-radius: 3px;
  font-size: 23px;
  display: block;
  height: 28px;
  border: 1px solid #E4E7EC;
}
/deep/.process--more{
  li{
    span i{
      font-size: 15px;
    }
  }
}
.isExpand{
  position: fixed;
  right: 0px;
  top: calc(50% - 15px);
  background: #CCCDCF;
  padding: 30px 3px;
  z-index: 9;
  border-radius: 4px 0 0 4px;
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
}
</style>
